import { createStoreBindings } from "mobx-miniprogram-bindings";
import { globalStore } from "../../../store/index";
import { getOrderDetail } from "../../../services/order";
import type { OrderRecord } from "../../../types/entities";

const statusMetaMap: Record<
  OrderRecord["status"],
  { label: string; desc: string }
> = {
  pending: { label: "待处理", desc: "厨师尚未接单" },
  accepted: { label: "已接收", desc: "厨师已确认订单" },
  rejected: { label: "已拒绝", desc: "订单已关闭" },
  cooking: { label: "制作中", desc: "美食正在出炉" },
  completed: { label: "已完成", desc: "期待你的评价" },
};

Page({
  data: {
    loading: true,
    order: null as OrderRecord | null,
    statusLabel: "",
    statusDesc: "",
    funTotal: 0,
    createdText: "",
    acceptedText: "",
    rejectedText: "",
    startedText: "",
    finishedText: "",
    isChef: false,
    ratingOptions: [1, 2, 3, 4, 5],
  },

  storeBindings: null as WechatMiniprogram.Component.TrivialInstance | null,

  onLoad(query: Record<string, string>) {
    this.storeBindings = createStoreBindings(this, {
      store: globalStore,
      fields: ["userProfile"],
    });
    const orderId = query.id || globalStore.activeOrderId;
    if (!orderId) {
      wx.showToast({ title: "订单不存在", icon: "none" });
      return;
    }
    this.setData({ isChef: globalStore.userProfile?.role === "chef" });
    this.loadOrder(orderId);
  },

  onUnload() {
    this.storeBindings?.destroyStoreBindings?.();
  },

  async loadOrder(orderId: string) {
    this.setData({ loading: true });
    try {
      const res = await getOrderDetail(orderId);
      globalStore.updateOrderSnapshot(res.order);
      const funTotal = res.order.items.reduce(
        (sum, item) => sum + item.funValue * item.quantity,
        0
      );
      const statusMeta =
        statusMetaMap[res.order.status] || { label: res.order.status, desc: "" };
      this.setData({
        order: res.order,
        funTotal,
        statusLabel: statusMeta.label,
        statusDesc: statusMeta.desc,
        createdText: this.formatTime(res.order.createdAt),
        acceptedText: this.formatTime(res.order.acceptedAt),
        rejectedText: this.formatTime(res.order.rejectedAt || res.order.closedAt),
        startedText: this.formatTime(res.order.startedAt),
        finishedText: this.formatTime(res.order.finishedAt || res.order.closedAt),
      });
    } catch (error) {
      console.error("加载订单详情失败", error);
      wx.showToast({ title: "加载失败", icon: "none" });
    } finally {
      this.setData({ loading: false });
    }
  },

  formatTime(value?: string) {
    if (!value) return "";
    return value.replace("T", " ").slice(0, 16);
  },

  handleRefresh() {
    const orderId = this.data.order?._id;
    if (orderId) {
      this.loadOrder(orderId);
    }
  },

  handleBack() {
    wx.navigateBack({ delta: 1 });
  },
});
